package com.example.demo.service.impl;

import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.demo.common.Result;
import com.example.demo.common.TokenUtils;
import com.example.demo.entity.User;
import com.example.demo.entity.dto.LoginDTO;
import com.example.demo.mapper.UserMapper;
import com.example.demo.service.IUserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import static com.example.demo.service.impl.AdminService.PASS_SALT;

@Service
public class UserService extends ServiceImpl<UserMapper, User>implements IUserService {
    @Autowired
    UserMapper userMapper;

    @Override
    public Result login(User user) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("student_id", user.getStudentId());
        User user1 = userMapper.selectOne(queryWrapper);
        if (user1 == null) {
            return Result.error("用户名不存在");
        }
        // 判断密码是否合法
        String securePass = securePass(user.getPassword());
        if (!securePass.equals(user1.getPassword())) {
            return Result.error("用户名或密码错误");
        }
        LoginDTO loginDto = new LoginDTO();
        BeanUtils.copyProperties(user1, loginDto);
        // 生成token
        String token = TokenUtils.genToken(String.valueOf(user1.getId()), user1.getPassword(),"user");
        loginDto.setToken(token);
        loginDto.setUsername(user1.getStudentId());
        return Result.success(loginDto);
    }

    private String securePass(String password) {
        return SecureUtil.md5(password + PASS_SALT);
    }

}
